package com.yochi.pictureseditor.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

import org.apache.commons.io.FileUtils;

import com.yochi.pictureseditor.constants.Constants;
import com.yochi.pictureseditor.images.Image;
import com.yochi.pictureseditor.images.ImageImpl;

import android.util.Log;

public class AppliedEffectsManager implements Serializable {
	
	private static final String TAG = "AppliedEffectsManager";
	private static final long serialVersionUID = 2096247203400909089L;
	
	private int appliedEffectsNumber;
	
	public AppliedEffectsManager() {
		this.appliedEffectsNumber = 0;
		createDirectories();
	}
	
	private void createDirectories() {
		final File root = new File(Constants.ROOT_PATH);
		if(!root.exists()) {
			root.mkdir();
		}
		final File tmp = new File(Constants.TMP_PATH);
		if(!tmp.exists()) {
			tmp.mkdir();
		}
	}
	
	public void resetManager() {
		final File tmp = new File(Constants.TMP_PATH);
		if(!tmp.exists()) {
			tmp.mkdir();
		} else {
			for(File f : tmp.listFiles()) {
				f.delete();
			}
		}
		appliedEffectsNumber = 0;
	}

	
	  ///////////////////
	 // SAVE AND LOAD //
	///////////////////
	
	public void saveEffectInstance(final Image image) {
		new Thread() {
			@Override 
			public void run() {
				try {
					PrintWriter out = new PrintWriter(Constants.TMP_PATH+appliedEffectsNumber);
					out.println(JsonSerializer.serialize(image));
					out.close();
					appliedEffectsNumber++;
					Log.i(TAG, "saveEffectInstance.appliedEffectsNumber="+appliedEffectsNumber);
				} catch (FileNotFoundException e) {
					Log.e(TAG, "FileNotFoundException : ",e);
				}
			}
		}.start();
	}
	
	public Image loadLastEffectInstance() {
		Image image = null;
		if(appliedEffectsNumber>=0) {
			try {
				int appliedEffectToLoad = appliedEffectsNumber-2;
				String stream = FileUtils.readFileToString(new File(Constants.TMP_PATH+appliedEffectToLoad));
				image = (Image) JsonSerializer.deserialize(stream, ImageImpl.class);
				File oldTmpFile = new File(Constants.TMP_PATH+appliedEffectsNumber);
				if(oldTmpFile.exists()) {
					oldTmpFile.delete();
				}
				this.appliedEffectsNumber--;
				Log.i(TAG, "loadLastEffectInstance.appliedEffectsNumber="+appliedEffectsNumber);
			} catch (IOException e) {
				Log.e(TAG, "IOException");
			}
		}
		return image;
	}
	
	public boolean hasEffectInstanceToLoad() {
		return appliedEffectsNumber==0 ? false : true;
	}

}
